import time

import requests
import yaml
from bs4 import BeautifulSoup
from PIL import Image

from notice import DingDingRobot

headers = {

    'Accept': 'application/json',
    'Accept-Language': 'en,zh-CN;q=0.9,zh;q=0.8',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': 'accounts.douban.com',
    'Origin': 'https://accounts.douban.com',
    'Referer': 'https://accounts.douban.com/passport/login',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/81.0.4044.122 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    'Cookie': 'bid=OFhomegA5fY; __utmc=30149280; douban-fav-remind=1; apiKey=; user_data={%22area_code%22:%22+86%22%2C%22number%22:%2218601087269%22%2C%22code%22:%223954%22}; vtoken=undefined; push_noty_num=0; __utmv=30149280.7258; douban-profile-remind=1; push_doumail_num=0; last_login_way=account; ll="108288"; __utmz=30149280.1587949995.6.2.utmcsr=accounts.douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/passport/login; ap_v=0,6.0; __utma=30149280.793823606.1587868272.1587952152.1587967834.8; _pk_ref.100001.2fad=%5B%22%22%2C%22%22%2C1587967847%2C%22https%3A%2F%2Fwww.douban.com%2Fdoumail%2F%22%5D; ps=y; _pk_id.100001.2fad=029d56dd77fceb36.1587868808.5.1587968424.1587949982.; '
              'login_start_time=',
}
session = requests.Session()

# username = input('请输入你的用户名：')
# password = input('请输入你的密码：')

url_login = 'https://accounts.douban.com/j/mobile/login/basic'
url_index = 'https://accounts.douban.com/passport/login'
url_mails = 'https://www.douban.com/doumail/'


def get_user():
    with open('/tmp/global.yaml', 'r+', encoding='utf-8') as config_file:
        config = yaml.safe_load(config_file)
        username = config['douban']['user']['username']
        password = config['douban']['user']['password']
        return username, password


username, password = get_user()

data = {
    'ck': '',
    'name': username,
    'password': password,
    'remember': 'true',
    'ticket': '',
}


def login():
    login_start_time = int(time.time() * 1000)
    headers['Cookie'] = headers['Cookie'] + str(login_start_time)
    html = session.post(url_login, headers=headers, data=data)
    print(html.text)
    response = session.get(url_mails)
    cookies = response.cookies

    cookies_string = requests.utils.dict_from_cookiejar(cookies)
    # for k,v in cookies_dict.items():
    #     cookies_string += k + '=' + v + '; '
    # print(cookies_dict)
    print(cookies_string)
    with open('/tmp/cookie_file.txt', 'w', encoding='utf-8') as cookies_file:
        cookies_file.write(cookies_string)


# def login(username, password, source='index_nav', redir='https://www.douban.com/', login='登录'):  # 模拟登入函数
#     caprcha_id, caprcha_link = get_captcha(index_url)  # 把get_captcha函数返回的值
#     if caprcha_id:  # 如果有caprcha_id,就执行解析caprcha_link网页信息，并把图片保存下来打开
#         img_html = session.get(caprcha_link)
#         with open('caprcha.jpg', 'wb') as f:
#             f.write(img_html.content)
#         try:
#             im = Image.open('caprcha.jpg')
#             im.show()
#             im.close()
#         except:
#             print('打开错误')
#         caprcha = input('请输入验证码：')  # 把看到的验证码图片输入进去1
#     data = {  # 需要传去的数据
#         'source': source,
#         'redir': redir,
#         'name': username,
#         'password': password,
#         'login': login,
#     }
#     if caprcha_id:  # 如果需要验证码就把下面的两个数据加入到data里面
#         data['captcha-id'] = caprcha_id
#         data['captcha-solution'] = caprcha
#     html = session.post(url, data=data, headers=headers)
#     print(session.cookies.items())


def get_captcha(param_url):  # 解析登入界面，获取caprcha_id和caprcha_link
    html = requests.get(param_url, headers=headers)
    soup = BeautifulSoup(html.text, 'xml')
    caprcha_link = soup.select('#captcha_image')[0]['src']
    # lzform > div.item.item-captcha > div > div > input[type="hidden"]:nth-child(3)
    caprcha_id = soup.select('div.captcha_block > input')[1]['value']
    return caprcha_id, caprcha_link


# login_url = 'https://www.douban.com/group/'
# xiaozu_html = session.get(login_url)
# soup = BeautifulSoup(xiaozu_html.text, 'lxml')
# # content > div > div.article > div.topics > table > tbody > tr:nth-child(1) > td.td-subject > a
# titles = soup.select('tr.pl > td.td-subject > a.title')
# for title in titles:
#     print(title['href'], title.string)


def get_cookies_from_file():
    with open('/tmp/cookie_file.txt', 'r+', encoding='utf-8') as cookies_file:
        cookies_string = cookies_file.readline()
        # print(cookies_string)
        return cookies_string.replace('\n', '')


def send_ding_msg(msg):
    DingDingRobot().make_text_msg(msg).send()


def receive_mail():
    headers['Cookie'] = get_cookies_from_file()
    headers['Referer'] = 'https://www.douban.com/group/tiantongyuan/'
    headers['Host'] = 'www.douban.com'
    headers['Upgrade-Insecure-Requests'] = '1'
    # print(headers)
    html = requests.get('https://www.douban.com/doumail/',
                        headers=headers)
    status = html.status_code
    reason = html.reason
    if status != 200 or reason != 'OK':
        # print("status is " + status, "reason: " + reason)
        raise Exception("status is " + status, "reason: " + reason)
    # print(html.text)
    soup = BeautifulSoup(html.text, 'html.parser')
    text_not_read = soup.select('.tabs')[0].text

    not_read_num = int(text_not_read[5:-4])
    if not_read_num > 0:
        print("have", not_read_num, "unread msg")
        send_ding_msg("[From DouMail]: " + "have " + str(not_read_num) + " unread msg")
    else:
        print("have no unread msg")


if __name__ == '__main__':
    while True:
        try:
            receive_mail()
        except Exception as e:
            send_ding_msg("[From DouMail]: " + str(e))
            break
        time.sleep(60)
